<template>
  <div class="category-management">
    <div class="header">
      <h2>分类管理</h2>
      <el-button type="primary" @click="openCategoryForm">
        <el-icon><Plus /></el-icon>
        新建分类
      </el-button>
    </div>

    <!-- 分类列表 -->
    <el-table 
      :data="categories" 
      style="width: 100%" 
      v-loading="loading.categories"
      empty-text="暂无分类数据"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" width="120" show-overflow-tooltip />
      <el-table-column prop="display_order" label="排序" width="80" />
      <el-table-column prop="description" label="描述" width="150" show-overflow-tooltip />
      <el-table-column label="关联项目" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.items && scope.row.items.length > 0" type="success">
            {{ scope.row.items.length }}个项目
          </el-tag>
          <el-tag v-else type="info">无项目</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button size="small" @click="editCategory(scope.row)">
            编辑
          </el-button>
          <el-button size="small" @click="manageCategoryPages(scope.row)">
            管理页面
          </el-button>
          <el-button size="small" @click="manageCategoryItems(scope.row)">
            管理项目
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="deleteCategory(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分类表单对话框 -->
    <CategoryForm
      v-model:visible="categoryFormVisible"
      :form-data="currentCategory"
      :is-edit="isEditCategory"
      :pages="pages"
      :items="items"
      :temp-page-relations="tempCategoryPageRelations"
      :temp-item-relations="tempCategoryItemRelations"
      @save="handleSaveCategory"
      @cancel="closeCategoryForm"
      @add-page="addPageToCategory"
      @remove-page="removePageFromCategory"
      @add-item="addItemToCategory"
      @remove-item="removeItemFromCategory"
    />

    <!-- 分类页面关系管理对话框 -->
    <RelationshipManager
      v-model:visible="categoryPagesDialogVisible"
      title="分类页面关系管理"
      :current-relations="currentCategoryPages"
      :available-items="availablePagesForCategory"
      item-key="id"
      item-label="title"
      @add-relation="addPageToCategory"
      @remove-relation="removePageFromCategory"
    />

    <!-- 分类项目关系管理对话框 -->
    <RelationshipManager
      v-model:visible="categoryItemsDialogVisible"
      title="分类项目关系管理"
      :current-relations="currentCategoryItems"
      :available-items="availableItemsForCategory"
      item-key="id"
      item-label="title"
      @add-relation="addItemToCategory"
      @remove-relation="removeItemFromCategory"
    />
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import CategoryForm from './CategoryForm.vue'
import RelationshipManager from './RelationshipManager.vue'

// Props
const props = defineProps({
  categories: {
    type: Array,
    default: () => []
  },
  pages: {
    type: Array,
    default: () => []
  },
  items: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Object,
    default: () => ({ categories: false })
  },
  tempCategoryPageRelations: {
    type: Array,
    default: () => []
  },
  tempCategoryItemRelations: {
    type: Array,
    default: () => []
  }
})

// Events
const emit = defineEmits([
  'save-category',
  'delete-category',
  'add-page-to-category',
  'remove-page-from-category',
  'add-item-to-category',
  'remove-item-from-category',
  'update-current-category-pages',
  'update-current-category-items',
  'refresh-data'
])

// 响应式数据
const categoryFormVisible = ref(false)
const categoryPagesDialogVisible = ref(false)
const categoryItemsDialogVisible = ref(false)
const currentCategory = ref({})
const isEditCategory = ref(false)
const currentCategoryId = ref(null)

// 计算属性
const currentCategoryPages = computed(() => {
  if (!currentCategoryId.value) return []
  return props.pages.filter(page => 
    page.categories && page.categories.some(cat => cat.id === currentCategoryId.value)
  )
})

const currentCategoryItems = computed(() => {
  if (!currentCategoryId.value) return []
  return props.items.filter(item => 
    item.categories && item.categories.some(cat => cat.id === currentCategoryId.value)
  )
})

const availablePagesForCategory = computed(() => {
  if (!currentCategoryId.value) return props.pages
  return props.pages.filter(page => 
    !page.categories || !page.categories.some(cat => cat.id === currentCategoryId.value)
  )
})

const availableItemsForCategory = computed(() => {
  if (!currentCategoryId.value) return props.items
  return props.items.filter(item => 
    !item.categories || !item.categories.some(cat => cat.id === currentCategoryId.value)
  )
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 打开分类表单
const openCategoryForm = () => {
  currentCategory.value = {
    name: '',
    slug: '',
    description: '',
    status: 'active'
  }
  isEditCategory.value = false
  categoryFormVisible.value = true
}

// 编辑分类
const editCategory = (category) => {
  currentCategory.value = { ...category }
  isEditCategory.value = true
  categoryFormVisible.value = true
  emit('update-current-category-pages', category.id)
  emit('update-current-category-items', category.id)
}

// 关闭分类表单
const closeCategoryForm = () => {
  categoryFormVisible.value = false
  currentCategory.value = {}
  isEditCategory.value = false
}

// 保存分类
const handleSaveCategory = (categoryData) => {
  emit('save-category', categoryData, isEditCategory.value)
  closeCategoryForm()
}

// 删除分类
const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    emit('delete-category', category.id)
  } catch {
    // 用户取消删除
  }
}

// 管理分类页面
const manageCategoryPages = (category) => {
  currentCategoryId.value = category.id
  emit('update-current-category-pages', category.id)
  categoryPagesDialogVisible.value = true
}

// 管理分类项目
const manageCategoryItems = (category) => {
  currentCategoryId.value = category.id
  emit('update-current-category-items', category.id)
  categoryItemsDialogVisible.value = true
}

// 添加页面到分类
const addPageToCategory = (pageId) => {
  emit('add-page-to-category', currentCategoryId.value, pageId)
}

// 从分类移除页面
const removePageFromCategory = (pageId) => {
  emit('remove-page-from-category', currentCategoryId.value, pageId)
}

// 添加项目到分类
const addItemToCategory = (itemId) => {
  emit('add-item-to-category', currentCategoryId.value, itemId)
}

// 从分类移除项目
const removeItemFromCategory = (itemId) => {
  emit('remove-item-from-category', currentCategoryId.value, itemId)
}
</script>

<style scoped>
.category-management {
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 6px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  height: 100vh;
  width: calc(100vw - 250px);
  margin: 0;
  position: fixed;
  top: 0;
  left: 250px;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-sizing: border-box;
  overflow: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 0;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 0;
  backdrop-filter: blur(10px);
  border: none;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
  width: 100%;
  margin-left: -12px;
  margin-right: -12px;
  padding-left: 28px;
  padding-right: 28px;
}

.header h2 {
  margin: 0;
  color: white;
  font-size: 28px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 16px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

/* 表格容器 */
.el-table {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 全局按钮样式美化 */
:deep(.el-button) {
  padding: 14px 24px !important;
  font-size: 16px !important;
  font-weight: 600 !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  transition: all 0.3s ease !important;
  border: none !important;
  min-height: 48px !important;
  min-width: 120px !important;
}

:deep(.el-button--default) {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important;
  color: #333 !important;
}

:deep(.el-button--default:hover) {
  background: linear-gradient(135deg, #e3e7f0 0%, #b1c1d8 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2) !important;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;
  color: white !important;
}

:deep(.el-button--success:hover) {
  background: linear-gradient(135deg, #0e8078 0%, #2dd865 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(17, 153, 142, 0.4) !important;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
  color: white !important;
}

:deep(.el-button--warning:hover) {
  background: linear-gradient(135deg, #ee82f9 0%, #f3455a 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(240, 147, 251, 0.4) !important;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%) !important;
  color: white !important;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #ff5252 0%, #e53e3e 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4) !important;
}

/* 表格操作按钮样式 */
:deep(.el-table .el-button) {
  padding: 8px 16px !important;
  font-size: 14px !important;
  min-height: 36px !important;
  min-width: 80px !important;
}

/* 操作列不换行 */
:deep(.el-table__body .el-table__row .el-table__cell:last-child) {
  white-space: nowrap !important;
}

:deep(.el-table__body .el-table__row .el-table__cell:last-child .cell) {
  white-space: nowrap !important;
  overflow: visible !important;
}

/* 图标样式 */
:deep(.el-icon) {
  margin-right: 8px !important;
  font-size: 18px !important;
}

/* 表格头部样式 */
:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  font-weight: 600;
  color: #303133;
}

/* 表格行样式 */
:deep(.el-table tbody tr:hover) {
  background: rgba(64, 158, 255, 0.05);
}

/* 标签样式 */
:deep(.el-tag) {
  padding: 6px 12px !important;
  font-size: 13px !important;
  font-weight: 600 !important;
  border-radius: 8px !important;
  border: none !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;
  color: white !important;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
  color: white !important;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%) !important;
  color: white !important;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%) !important;
  color: white !important;
}

/* 滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-track) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}
</style>